package vip.xiaonuo.modular.util;

import vip.xiaonuo.modular.entity.response.Response;
import io.swagger.annotations.ApiModelProperty;

import java.io.Serializable;

/**
 * @Author tuchaoren
 * @Date 2021-06-24
 **/
public class PlatformResponse<T> implements Serializable, IResponse {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value="响应编码",example="1")
    private int code;
    @ApiModelProperty(value="响应信息",example="成功")
    private String msg;
    @ApiModelProperty(value="响应内容")
    private T data;

    public PlatformResponse() {
        this(ResultCode.SUCCESS, null);
    }

    public PlatformResponse(int code){
        this(code, "", null);
    }

    public PlatformResponse(T data){
        this(ResultCode.SUCCESS, data);
    }

    public PlatformResponse(int code, String message) {
        this(code, message, null);
    }

    public PlatformResponse(IResultCode resultCode){
        this(resultCode, null);
    }


    public PlatformResponse(IResultCode resultCode, T data){
        this.code = resultCode.getCode();
        this.msg = resultCode.getMsg();
        this.data = data;
    }

    public PlatformResponse(int code, String message, T data) {
        this.code = code;
        this.msg = message;
        this.data = data;
    }

    public static PlatformResponse ok(String msg){
        return new PlatformResponse<>(OK_STATUS, msg);
    }

    public static <T extends Serializable> PlatformResponse<T> ok(String msg, T data){
        return new PlatformResponse<>(OK_STATUS, msg, data);
    }
    public static <T extends Serializable> PlatformResponse<T> ok(T data){
        return new PlatformResponse<>(OK_STATUS, "操作成功", data);
    }

    public static PlatformResponse failed(String message){
        return new PlatformResponse<>(FAIL_STATUE, message);
    }

    public static PlatformResponse failed(IResultCode resultCode){
        return new PlatformResponse<>(resultCode.getCode(),resultCode.getMsg());
    }

    public static <T> T getDataAndException(Response<T> r) {
        if (null != r) {
            if ("0".equals(r.getCode())) {
                return r.getData();
            } else {
                // 抛出接口返回的异常信息
                throw new CommonException(r.getMessage());
            }
        }
        return null;
    }

    @Override
    public int getCode() {
        return 0;
    }

    @Override
    public String getMsg() {
        return null;
    }
}
